package com.huan.study.ajax.download;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.google.common.collect.Lists;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author huan.fu 2020-06-25 - 13:05
 */
@RestController
@CrossOrigin("*")
public class ExcelDownloadController {

    private static final List<User> USERS = Lists.newArrayList(
            User.builder().age(20).name("张三").build(),
            User.builder().age(18).name("李四").build(),
            User.builder().age(25).name("王五").build()
    );

    @PostMapping("export")
    public void export(HttpServletResponse response) throws IOException {
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=export.xlsx");
        ExportParams exportParams = new ExportParams("学生信息", "导出测试", ExcelType.XSSF);
        ExcelExportUtil.exportExcel(exportParams, User.class, new ArrayList<>(USERS)).write(response.getOutputStream());
    }
}
